package com.yue.spitter.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.crypto.password.StandardPasswordEncoder;

/**
 * 功能描述: TODO <br/>
 * 创建时间: 2016/7/25<br/>
 *
 * @author QiuYang
 */
@Configuration
@EnableWebSecurity    // 启用Web安全性
//@EnableWebMvcSecurity   // 启用Spring mvc安全性
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {    // 选择查询用户详细信息的服务
        // 1. 使用基于内存的用户存储
//        auth.inMemoryAuthentication()
//                .withUser("user").password("password").roles("USER").and()
//                .withUser("admin").password("password").roles("USER", "ADMIN");

        // 2. 基于数据库表进行认证
//        auth.jdbcAuthentication()
//                .dataSource(dataSourece)
//                .usersByUsernameQuery("select username, password, true from Spitter wehre userName = ?")
//                .authoritiesByUsernameQuery("select username, 'ROLE_USER' from Spitter where username = ?")
//                .passwordEncoder(new StandardPasswordEncoder("53cr3t"));

        // 3. 基于LDAP进行认证
        auth.ldapAuthentication()
                .userSearchBase("ou=people")
                .userSearchFilter("(uid={0}")
                .groupSearchBase("ou=groups")
                .groupSearchFilter("member={0}")
                .contextSource().url("ldap://habuma.com/dc=habuma, dc=com")
                .and()
                .passwordCompare()
                .passwordEncoder(new Md5PasswordEncoder())
                .passwordAttribute("password");

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {    // 拦截请求
        http.authorizeRequests()
                .antMatchers("/spitters/me").authenticated()
                .antMatchers(HttpMethod.POST, "/spittles").authenticated()
                .anyRequest().permitAll();
    }
}
